using MultiAgentsShared;
using static MultiAgentsClient.Manager.MessageManager;

namespace MultiAgentsClient.Presentation;

public partial record ReplyAssistantModel
{
    private readonly IEventBus eventBus;
    public IState<bool> IsReplyAssistantDisplay => State.Value(this, () => false);
    public IListState<string> ReplyAssistantOptions => ListState<string>.Empty(this);
    public IState<bool> AllowToSendMessage => State.Value(this, () => true);

    public ReplyAssistantModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<AllowSendMessageCommand>(async cmd => { await AllowSendMessageCommandHandler(); });
        eventBus.Subscribe<ReplyAssistantCloseCommand>(async cmd => { await Close(); });
        eventBus.Subscribe<ReplyAssistantOptionsCommand>(async cmd => { await ReplyAssistantOptionsResponseCommandHandler(cmd); });
    }

    public async ValueTask SendSelectedOption(string selectedOption)
    {
        await IsReplyAssistantDisplay.SetAsync(false, default);

        if (await AllowToSendMessage)
        {
            eventBus.Publish(new SendUserMessageCommand(selectedOption, []));
            await Close();
        }
    }

    private async ValueTask Close()
    {
        await ReplyAssistantOptions.RemoveAllAsync(match: item => true, ct: default);
        await IsReplyAssistantDisplay.SetAsync(false, default);
    }

    private async ValueTask ReplyAssistantOptionsResponseCommandHandler(ReplyAssistantOptionsCommand cmd)
    {
        if (await AllowToSendMessage == false)
        {
            return;
        }

        await ReplyAssistantOptions.RemoveAllAsync(match: item => true, ct: default);
        foreach (string option in cmd.Options)
        {
            await ReplyAssistantOptions.AddAsync(option);
        }

        await IsReplyAssistantDisplay.SetAsync(true, default);
    }

    private async ValueTask AllowSendMessageCommandHandler()
    {
        await AllowToSendMessage.Set(true, default);
    }
}
